/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/store/';
import router from '@/router/router'
import { serialize, deepClone, getAuthorization } from '@/util/util'
import { Message } from 'element-ui'
import website from '@/config/website';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
axios.defaults.timeout = 20000;
//返回其他状态码
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 600; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
  showSpinner: false
});
let ajaxdata = {};
//HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start() // start progress bar
  const meta = (config.meta || {});
  const isToken = meta.isToken === false;
  if (!config.headers['Authorization']) {
    config.headers['Authorization'] = getAuthorization(website.clientCode, website.clientSecret);
  }
  if (store.getters.token && !isToken) {
    config.headers[window.$KEY.AUTH] = store.getters.tokenType + " " + store.getters.token;
  }else {
    // 在未登录的情况下需要在header中传递通过域名获取到的租户Code
    if (website.isTenant) {
      if (store.getters.tenantCode) {
        config.headers['Tenant-Code'] = store.getters.tenantCode
      }
    }
  }

  //headers中配置serialize为true开启序列化
  if (['post', 'put', 'delete'].includes(config.method) && meta.isSerialize === true) {
    let ajaxurl = config.url.replace(window.home_url, '');
    ajaxdata[ajaxurl] = deepClone(config.data);
    config.data = serialize(config.data);
  }
  // }
  return config
}, error => {
  return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
  NProgress.done();
  let status = Number(res.data.code) || 200;
  const statusWhiteList = website.statusWhiteList || [];
  const message = res.data.message || res.data['msg'] || '未知错误';
  //如果在白名单里则自行catch逻辑处理
  if (statusWhiteList.includes(status)) return Promise.reject(res);
  //如果是407则跳转到登录页面
  if (res.status === 401) {
    if (status === 407) {
      Message({
        message: '请求未经授权，请登录获取权限！',
        type: 'error'
      });

      setTimeout(() => {
        store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }));
      }, 3000);
      return Promise.reject(new Error(message));
    }
  }

  if (status === 500) {
    let msg = '系统异常，请联系管理员';
    if (message.search("演示环境") !== -1){
      msg = '演示环境不支持操作';
    }

    Message({
      message: msg,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  } else if (status !== 200 && status !== 201) {
    Message({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  }
  return res;
}, error => {
  NProgress.done();
  return Promise.reject(new Error(error));
})

export default axios;